package common.realm;

import common.entity.User;
import common.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        Set<String> rolesset = new HashSet<>();
        rolesset.add(user.getRole());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(rolesset);

        info.addStringPermission(user.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findById(token.getUsername());
        if(user != null){
            return new SimpleAuthenticationInfo(user,user.getPassword(), getName());
        }
        return null;
    }
}
